package com.qingyun.video.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class MergeVideoMp3 {

	private String ffmpegEXE;

	public MergeVideoMp3(String ffmpegEXE) {
		super();
		this.ffmpegEXE = ffmpegEXE;
	}

	/**
	 * @throws Exception
	 * @Description: videoInputPath:Mp4资源文件
	 * @Description: mp3InputPath:Mp3资源文件
	 * @Description: seconds:截取 mp3 0到N秒  生成mp4背景音乐
	 * @Description: videoOutputPath:最终文件路径,绝对路径
	 */
	public synchronized void convertor(String videoInputPath, String mp3InputPath, double seconds, String videoOutputPath) throws Exception {
		File file = new File(videoOutputPath);
		if (file.exists()) {
			return;
		}
		if (!file.getParentFile().isDirectory()) {
			file.getParentFile().mkdirs();
		}
		List<String> command = new ArrayList<>();
		command.add(ffmpegEXE);
		command.add("-an");
		command.add("-i");
		command.add(videoInputPath);

		command.add("-i");
		command.add(mp3InputPath);

//		command.add("-t");
//		command.add(String.valueOf(seconds));
		command.add("-preset");
		command.add("faster");

		command.add("-shortest");
		command.add("-y");
		command.add(videoOutputPath);
		ProcessBuilder builder = new ProcessBuilder(command);
		Process process = builder.start();
		InputStream errorStream = process.getErrorStream();
		InputStreamReader inputStreamReader = new InputStreamReader(errorStream);
		BufferedReader br = new BufferedReader(inputStreamReader);
		//@SuppressWarnings("unused")
		@SuppressWarnings("unused")
		String line = "";
		while ((line = br.readLine()) != null) {
		}
		//删除去掉声音的视频文件 此方法最好放在这个位置,不要拉到前面
//		File oldFile = new File(videoInputPath);
//		oldFile.delete();
		if (br != null) {
			br.close();
		}
		if (inputStreamReader != null) {
			inputStreamReader.close();
		}
		if (errorStream != null) {
			errorStream.close();
		}
	}

}
